<template>
  <div class="dynamic-detail-wrap">
    <div v-for="(construct, conIndex) in constructions" :key="construct.key" class="module-item">
      <div v-if="isShowTitle(construct.key)" :style="{ 'marginTop': conIndex === 0 ? '0px' : '20px' }" style="display:flex;align-items:center;margin-bottom:10px;">
        <div><Title :title="construct.title" /></div>
        <div style="flex:1;"/>
      </div>
      <div style="padding-left:12px;">
        <el-form v-if="detailData" :class="{'mobile-el-form': showMobilePage}" :label-width="showMobilePage ? '100px' : '180px'" :label-position="showMobilePage?'left':'right'" class="customer-form">
          <el-row v-for="(child, index) in construct.children" :key="index" :gutter="8" :class="construct.key === 'createInfo' && device !== 'mobile' ? 'dividing' : ''" class="content">
            <el-col v-for="item in child" :span="24 / child.length" :key="item.key" :class="{'fold-label':showMobilePage}">
              <el-form-item v-if="item.type === 'mulLevelInfo'" :label="item.label" >
                <span>{{ getMulLevelInfo(item.keys, item.module) }}</span>
              </el-form-item>
              <!-- 加密字段 -->
              <el-form-item
                v-if="detailData[item.module] && item.type === 'commonInfo' && item.showType === 'secret' && (processData.processStatus === 4 || processData.processStatus === 3)"
                :label="item.label"
                :label-width="item.labelWidth">
                <SecretText :log-text="getLogText(detailData[item.module], item)" :origin-text="detailData[item.module][item.key]" />
              </el-form-item>
              <el-form-item v-else-if="detailData[item.module] && item.type === 'commonInfo' && (item.showContractType ? showRadioItem(detailData[item.module].type, item.showContractType) : true)" :label="item.label" :label-width="item.labelWidth ? item.labelWidth : ''">
                <span style="word-break: break-word">{{ (detailData[item.module][item.key] || detailData[item.module][item.key] === 0) ? detailData[item.module][item.key] : '--' }}</span>
              </el-form-item>
              <!-- 特别的 直接写 -->
              <el-form-item v-if="item.type === 'relateProcess' && detailData[item.module].relatedFlowCode" label="关联流程:">
                <span class="link" @click="linkToRelated(item)">{{ detailData[item.module].relatedFlowCode }}</span>
              </el-form-item>
              <!-- 含tooltip的信息展示 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'tooltipInfo'" :label="item.label">
                <ToolTip :content="detailData[item.module][item.key]" />
              </el-form-item>
              <!-- 自动生成合同编号 -->
              <el-form-item v-if="item.type === 'generateCode'" :label="item.label">
                <span v-if="detailData[item.module][item.key] || (code && isCurrentVersion)">{{ detailData[item.module][item.key] || code }}</span>
                <el-button
                  v-else-if="canGenerateCode"
                  :loading="generateCodeLoading"
                  size="small"
                  type="primary"
                  @click="generateCode">自动生成</el-button>
                <span v-else>--</span>
              </el-form-item>
              <!-- 合同回收 -->
              <el-form-item v-if="item.type === 'recycleContract'" :label="item.label">
                <ContractRecycle :params="detailData[item.module][item.key]" :is-current-version="isCurrentVersion" :process-status="processData.processStatus" :set-events="operateData.setEvents" :modify-auth="item.uploadAuth" :check-auth="item.checkAuth" />
              </el-form-item>
              <!-- 单选框类型-->
              <el-form-item v-if="item.type === 'radioInfo'" :label="item.label" :style="{'margin-bottom': stampRequired ? (showMobilePage ? '48px !important' : '16px') : '0'}" class="radio-form-item">
                <radioEdit :can-edit="canEditRadio" :params="detailData[item.module][item.key]" :stamp-required="stampRequired" :is-in-stamp-event="isInStampEvent" :options="item.option" :title="'修改盖章类型'" :text="renderStampText(detailData[item.module][item.key])" @changeRadioValue="changeRadioValue" />
                <div v-if="isInStampEvent && canEditRadio" class="radio-tip-border" />
              </el-form-item>
              <!-- 选择框类型的下拉框选择 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'selectInfo' && showRadioItem(detailData[item.module].type, item.showContractType) && (item.hasValToShow ? (detailData[item.module][item.key] || detailData[item.module][item.key] === 0) : true)" :label="item.label" :class="{ 'label-decoration': item.hasValToShow }">
                <div :class="getTypeClass(item, detailData[item.module][item.key])">{{ detailData[item.module][item.key] | mapOptions(item.option) }}</div>
              </el-form-item>
              <!-- tooltip类型的选择框类型的下拉框选择 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'tooltipSelectInfo' && (!isPartTimeWorker || (isPartTimeWorker && item.key !== 'tempSource'))" :label="item.label">
                <div style="display:flex;">
                  <el-tooltip placement="top" effect="dark">
                    <div slot="content" style="max-width: 200px;">{{ detailData[item.module][item.key] | mapOptions(item.option) }}</div>
                    <span class="overflow" style="display: inline-block;max-width: 80%;">{{ detailData[item.module][item.key] | mapOptions(item.option) }}</span>
                  </el-tooltip>
                </div>
              </el-form-item>
              <!-- 合同日期 -->
              <contract-date v-if="detailData[item.module] && item.type === 'contractDate'" :date-info="detailData[item.module][item.key]" :show-mobile-page="showMobilePage"/>
              <!-- textarea 类型 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'textareaInfo'" :label="item.label" :label-width="item.labelWidth">
                <span>{{ detailData[item.module][item.key] || item.emptyText }}</span>
              </el-form-item>
              <!-- 合同附件 -->
              <el-form-item
                v-if="detailData[item.module] && item.type === 'attachment'&& item.showType === 'secret' && (processData.processStatus === 4 || processData.processStatus === 3)"
                :label="item.label"
                :label-width="item.labelWidth"
                class="attachment">
                <SecretText
                  v-if="detailData[item.module][item.key] && detailData[item.module][item.key].length"
                  :log-text="getLogText(detailData[item.module], item)"
                  data-type="field" >
                  <template slot="field">
                    <upAttachment
                      ref="uploadFile"
                      :only-file-list="true"
                      :hide-clip-up="true"
                      :hide-confirm="true"
                      :is-disabled="true"
                      :file-list="detailData[item.module][item.key]"
                      file-container-top="0px"
                      btn-text="上传文件"
                      @downloadSuccess="downloadSuccess($event, detailData)" />
                  </template>
                </SecretText>
                <span v-else>&nbsp;--</span>
              </el-form-item>
              <el-form-item v-else-if="detailData[item.module] && item.type === 'attachment'" :label="item.label" :label-width="item.labelWidth" class="attachment">
                <upAttachment
                  v-if="detailData[item.module][item.key] && detailData[item.module][item.key].length"
                  ref="uploadFile"
                  :only-file-list="true"
                  :hide-clip-up="true"
                  :hide-confirm="true"
                  :is-disabled="true"
                  :file-list="detailData[item.module][item.key]"
                  file-container-top="0px"
                  btn-text="上传文件"
                  @downloadSuccess="downloadSuccess($event, detailData)" />
                <span v-else>&nbsp;--</span>
              </el-form-item>
              <!-- 关联合同编号
              <el-form-item v-if="detailData[item.module] && item.type === 'relevanConstruct'" :label="item.label" :label-width="item.labelWidth">
                <relevan-construct :is-exhibition="true" :params="detailData[item.module][item.key]" />
              </el-form-item>
              -->
              <!-- 人事采购合同中的合作日期/付款方式模块 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'staffAdminCooperDate' && detailData[item.module][item.key]" :label="item.label" :label-width="item.labelWidth">
                <staff-cooper-single-buy v-if="detailData[item.module][item.key].type === 1 || detailData[item.module][item.key].type === 3" :is-exhibition="true" :params="detailData[item.module][item.key]" />
                <staff-entrust-service v-else-if="detailData[item.module][item.key].type === 2" :is-exhibition="true" :params="detailData[item.module][item.key]" />
                <div>兼职人员合作</div>
              </el-form-item>
              <!-- 参考授权单信息模块中的付授权模块 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'deadlineSelect'" :label="item.label" :label-width="item.labelWidth">
                <deadline-select :params="detailData[item.module][item.key]" :is-exhibition="true" />
              </el-form-item>
              <!-- 授权单信息模块中的付款期限模块 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'autorPayDeadline' && detailData[item.module][item.key]" :label="item.label" :label-width="item.labelWidth">
                <base-author-royalty v-if="detailData[item.module][item.key].type === 1" :params="detailData[item.module][item.key]" :is-exhibition="true" :show-mobile-page="showMobilePage"/>
                <author-commission v-else :params="detailData[item.module][item.key]" :is-exhibition="true" />
              </el-form-item>
              <!-- 特殊的签约对方 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'oppCompanySelect'" :label="item.label" :label-width="item.labelWidth">
                <opp-company-select :params="detailData[item.module]" :is-exhibition="true" :detail-data="detailData" />
              </el-form-item>
              <!-- 时间范围显示 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'dateRangeTime'" :label="item.label" :label-width="item.labelWidth">
                <date-range-picker :params="detailData[item.module][item.key]" :is-exhibition="true" />
              </el-form-item>
              <!-- 日期显示 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'dateTime'" :label="item.label" :label-width="item.labelWidth">
                <span v-if="detailData[item.module][item.key]">{{ detailData[item.module][item.key] / 1000 | standardFormat(item.timeType) }}</span>
                <span v-else>--</span>
              </el-form-item>
              <!-- 结算周期选择 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'otherSelectGroup' && (item.hasValToShow ? validCooperModel(detailData[item.module][item.key], item.typeField) : true)" :label="item.label" :label-width="item.labelWidth" :class="{ 'label-decoration': item.hasValToShow }">
                <other-select-group :params="detailData[item.module][item.key]" :is-exhibition="true" :module-name="item.module + '.' + item.key" :type-field="item.typeField" :name-field="item.nameField" :options="item.options" :other-value="item.otherValue"/>
              </el-form-item>
              <!-- 合作平台 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'cooperAccountSelect' && (item.hasValToShow ? validCooperPlatforms(detailData[item.module][item.key]) : true)" :label="item.label" :label-width="item.labelWidth" :class="{ 'label-decoration': item.hasValToShow }">
                <cooper-account-select v-model="detailData[item.module][item.key]" :is-exhibition="true" :module-name="item.module + '.' + item.key" :show-mobile-page="showMobilePage"/>
              </el-form-item>
              <!-- 复选框带输入框组件 看考kol类分成/收益功能 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'checkboxInputs' && (item.hasValToShow ? validEarningsData(detailData[item.module][item.key]) : true)" :label="item.label" :label-width="item.labelWidth" :class="{ 'label-decoration': item.hasValToShow }">
                <checkbox-inputs :params="detailData[item.module][item.key]" :is-exhibition="true" :module-name="item.module + '.' + item.key" :checkbox-group-field="item.checkboxGroupField" :input-items="item.inputItems" />
              </el-form-item>
              <!-- 电商模块 -->
              <e-commerce-group
                v-if="detailData[item.module] && item.type === 'eCommerceGroup'"
                :key="item.key"
                v-model="detailData[item.module]"
                :is-exhibition="true"
                :is-complate="processData.processStatus === 4 || processData.processStatus === 3"
                :module-name="item.module"
                :contract-code="detailData.contractInfo.code"
                :show-mobile-page="showMobilePage"/>
              <!-- 分期时间选择 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'dateMulPicker'" :label="item.label" :label-width="item.labelWidth">
                <date-mul-picker :params="detailData[item.module][item.key]" :is-exhibition="true" :module-name="item.module + '.' + item.key" target-field="payDate" />
              </el-form-item>
              <!-- 涉及金额 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'moneyInvolved' && detailData[item.module][item.key]" :label="item.label" :label-width="item.labelWidth">
                <money-involved v-if="detailData[item.module][item.key].isMoneyInvolved === 1" :is-exhibition="true" :params="detailData[item.module][item.key]" :module-name="item.module + '.' + item.key" />
                <span v-else>否</span>
              </el-form-item>
              <!-- KOL类：公司/达人分成比例 -->
              <el-form-item v-if="detailData[item.module] && item.type === 'ratioGroup'" :label="item.label" :label-width="item.labelWidth">
                <div v-if="detailData[item.module][item.key] || detailData[item.module][item.key] === 0">
                  公司：{{ `${detailData[item.module][item.key]}%` }}，达人：{{ getTalentSharingRatio(detailData[item.module][item.key]) }}
                </div>
                <div v-else>--</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <empty-placeholder v-else style="height: 400px;" />
      </div>
    </div>
  </div>
</template>
<script>
import Title from '@/components/Title';
import options from '../../module/options';
import ContractDate from './component/contractDate';
import { hasRouteAuth } from '@/utils/permission';
import { generateCode } from '@/api/legal';
import { mapOptions } from '@/filters';
import upAttachment from '@/components/Common/upAttachment/index';
import RelevanConstruct from '../../create/module/relevanConstruct.vue';
import StaffCooperSingleBuy from '../../create/module/staffCooperSingleBuy.vue';
import StaffEntrustService from '../../create/module/staffEntrustService.vue';
import DeadlineSelect from '../../create/module/deadlineSelect';
import BaseAuthorRoyalty from '../../create/module/baseAuthorRoyalty';
import AuthorCommission from '../../create/module/authorCommission';
import OppCompanySelect from '../../create/module/oppCompanySelect';
import DateRangePicker from '../../create/module/dateRangePicker';
import OtherSelectGroup from '../../create/module/otherSelectGroup';
import CooperAccountSelect from '../../create/module/cooperAccountSelect';
import CheckboxInputs from '../../create/module/checkboxInputs';
import ECommerceGroup from '../../create/module/eCommerceGroup';
import DateMulPicker from '../../create/module/dateMulPicker';
import MoneyInvolved from '../../create/module/moneyInvolved';
import { standardFormat } from '@/filters/date';
import ContractRecycle from '@/components/contractRecycle/contractRecycle';
import radioEdit from '@/components/Common/radioEdit';
import { decrypt } from '@/utils';
import math from '@/utils/math';
import { mapState } from 'vuex';
import { attachmentDownload } from '@/api/legal';

export default {
  name: 'DynamicDetail',
  components: {
    Title,
    ContractDate,
    upAttachment,
    RelevanConstruct,
    StaffCooperSingleBuy,
    StaffEntrustService,
    DeadlineSelect,
    BaseAuthorRoyalty,
    AuthorCommission,
    OppCompanySelect,
    DateRangePicker,
    OtherSelectGroup,
    CooperAccountSelect,
    CheckboxInputs,
    ECommerceGroup,
    DateMulPicker,
    ContractRecycle,
    MoneyInvolved,
    radioEdit
  },
  filters: {
    mapOptions,
    standardFormat
  },
  props: {
    detailData: {
      type: Object,
      default: () => { return null; }
    },
    constructions: {
      type: Array,
      default: () => {
        return null;
      }
    },
    operateData: {
      type: Object,
      default: () => {
        return null;
      }
    },
    processData: {
      type: Object,
      default: () => {
        return null;
      }
    },
    showMobilePage: {
      type: Boolean,
      default: false
    },
    stampRequired: {
      type: Boolean,
      default: false
    },
    isCurrentVersion: {// 是否当前版本
      type: Boolean,
      default: true
    },
    isPartTimeWorker: { // 购销合同选中兼职人员合作
      type: Boolean,
      default: false
    },
    attachmentCardId: { // 附件记录第一个卡片的id
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      options,
      generateCodeLoading: false,
      code: ''
    };
  },
  computed: {
    ...mapState({
      'device': state => state.app.device
    }),
    canGenerateCode() {
      if (this.operateData.setEvents && this.operateData.setEvents.includes(2) && this.isCurrentVersion) {
        return true;
      }
      return false;
    },
    canEditRadio() {
      return this.operateData.setEvents && this.operateData.setEvents.includes(12) && this.operateData.auth.includes(2) && this.isCurrentVersion;
    },
    // 是否到达盖章事件节点且没有选择盖章类型
    isInStampEvent() {
      return this.operateData.setEvents && this.operateData.setEvents.includes(12) && ![0, 1].includes(this.detailData.contractInfo.stampType);
    }
  },
  methods: {
    hasRouteAuth,
    isShowTitle(key) {
      if (this.detailData) {
        if (this.detailData[key] instanceof Array) {
          return this.detailData[key].length > 0;
        } else {
          return !!this.detailData[key];
        }
      } else {
        return false;
      }
    },
    changeRadioValue(data) {
      this.$emit('changeRadioValue', data);
    },
    generateCode() {
      try {
        this.generateCodeLoading = true;
        generateCode({ id: Number(decrypt(this.$route.params.id)) }).then(res => {
          this.generateCodeLoading = false;
          if (res.code === 200) {
            this.code = res.data;
          } else {
            this.$message.closeAll();
            this.$message.warning(res.message);
          }
        }).catch(err => {
          this.generateCodeLoading = false;
          this.$message.closeAll();
          if (err.message && err.code === 403) {
            this.$message.error(err.message);
          } else {
            this.$message.error('合同编号生成失败，请稍后再试');
          }
          console.log(err);
        });
      } catch (error) {
        this.generateCodeLoading = false;
        console.log(error);
      }
    },
    getMulLevelInfo(keys, moduleName) {
      let value = this.detailData[moduleName];
      if (!value) return;
      keys.forEach(item => {
        if (value) {
          value = value[item];
        }
      });
      return value || '--';
    },
    linkToRelated(item) {
      const routeUrl = this.$router.resolve({
        name: 'contractDetail',
        params: {
          id: this.detailData[item.module].relatedId
        },
        query: {
          processId: this.detailData[item.module].relatedProcessId
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    showRadioItem(status, showType) {
      if (!showType) return true;
      return status === showType;
    },
    renderStampText(v) {
      const map = ['实体章', '电子章'];
      if (!v && v !== 0) return '--';
      return map[v];
    },
    getTypeClass(item, key) {
      if (item.label === '合同类型:') {
        return `contract-type contract-type-${key}`;
      }
      return;
    },
    getLogText(data, item) {
      return `合同详情${data.code}的${item.label.replace(':', '')}`;
    },
    getTalentSharingRatio(val) {
      return `${math.subtract(100, val)}%`;
    },
    validEarningsData(data) { // kol合同历史字段分成/收益 有值才展示
      if (!data) return false;
      return !!data.guaranteeSum || !!data.proportion;
    },
    validCooperModel(data, typeField) { // kol合同历史合作模式 有值才展示
      return data && (data[typeField] || data[typeField] === 0);
    },
    validCooperPlatforms(list) { // kol合同历史字段合作平台/账号 有值才展示
      if (!Array.isArray(list) || !list.length) return false;
      if (list.length > 1) return true;
      return !Object.keys(list[0]).every(key => !list[0][key]);
    },
    downloadSuccess(val, item) {
      const data = {
        id: this.attachmentCardId,
        businessId: item.id,
        name: val
      };
      attachmentDownload(data).then(res => {
        if (res.code === 200) {
          this.$emit('refreshAttachment');
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.customer-form {
  &::v-deep {
    .el-form-item {
      height: auto;
      line-height: unset;
      margin-bottom: 0px;
      .el-form-item__label {
        height: auto;
        line-height: unset;
        color: #999;
      }
      .el-form-item__content {
        height: auto;
        line-height: unset;
      }
    }
    .order-import-button .file-container {
      margin-top: 0;
    }
  }
  .dividing{
    &::v-deep {
      .el-col {
        .el-form-item__content {
          border-right: 1px solid #EBEEFD;
        }
        &:nth-child(2n) {
          .el-form-item__content {
            border-right: none;
          }
        }
        &:last-child {
          .el-form-item__content {
            border-right: none;
          }
        }
      }
    }
  }
  .radio-form-item {
    position: relative;
    ::v-deep .el-form-item__label {
      position: relative;
      z-index: 2;
    }
    .radio-tip-border {
      position: absolute;
      top: -4px;
      left: -180px;
      background-color: #fafbff;
      border: 1px solid #e6edff;
      border-radius: 8px;
      width: 360px;
      height: 40px;
    }
  }
}
.fold-label {
  &::v-deep {
    .el-form-item__label, .el-form-item__content{
      line-height: 1.1 !important;
    }
    .el-form-item {
      margin-bottom: 12px !important;
    }
  }
}
.attachment {
  &::v-deep {
    .el-form-item__label, .el-form-item__content{
      line-height: 32px !important;
    }
  }
}
.overflow {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
.contract-type {
    border-radius: 10px;
    width: fit-content;
    padding: 2px 10px;
    font-size: 12px;
    font-family: PingFangSC-Regular;
    height: 20px;
    line-height: 16px;
    margin-top: 6px;
  &.contract-type-1 {
    background-color: #FFF0FA;
    color: #FD6DD1;
  }
  &.contract-type-2 {
    background-color: #EFF4FF;
    color: #406EFF;
  }
  &.contract-type-3 {
    background-color: #E2F8F2;
    color: #31CC9C;
  }
  &.contract-type-4 {
    background-color: #F4F2FF;
    color: #A691FF;
  }
  &.contract-type-5 {
    background-color: #FFF2EB;
    color: #FD8546;
  }
  &.contract-type-6 {
    background-color: #FFF8EA;
    color: #FFBC3D;
  }
  &.contract-type-7 {
    background-color: #F2F8EC;
    color: #87BF69;
  }
  &.contract-type-8 {
    background-color: #EBF6FF;
    color: #48B8FF;
  }
  &.contract-type-9 {
    background-color: #F3F8E2;
    color: #91B125;
  }
}
.mobile-el-form {
  .radio-form-item {
    margin-bottom: 36px !important;
    .radio-tip-border {
      left: -100px;
      width: 280px;
      height: 24px;
    }
  }
}
.content {
  &::v-deep {
    .el-col {
      padding-left: 0 !important;
    }
  }
}
.label-decoration {
  ::v-deep .el-form-item__label {
    text-decoration: line-through;
  }
}
</style>
